package com.netcracker.ui.servlet;

import com.netcracker.ui.helper.UIHelper;
import com.netcracker.entity.Right;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.NullDataException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

@WebServlet(name = "DownloadServlet", urlPatterns = {"/DownloadServlet"})
public class DownloadServlet extends HttpServlet {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DownloadServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getContextPath();
        Right right = (Right) request.getSession().getAttribute("right");
        if (right != null && (right.equals(Right.USER) || right.equals(Right.ADMIN))) {
            Integer bookID = Integer.parseInt(request.getParameter("bookID"));
            ServiceFacade serviceFacade = UIHelper.getServiceFacade();
            File bookFile;
            try {
                bookFile = serviceFacade.getBookService().downloadBookFile(bookID);
                response.setContentType("application/download");
                response.addHeader("Content-Disposition", "attachment; filename=" + bookFile.getName());
                response.setContentLength((int) bookFile.length());

                FileInputStream fileInputStream = new FileInputStream(bookFile);
                OutputStream responseOutputStream = response.getOutputStream();
                int bytes;
                while ((bytes = fileInputStream.read()) != -1) {
			responseOutputStream.write(bytes);
                }
                request.getRequestDispatcher("BookInfo.jsp").forward(request, response);
             } catch (DataTransmittingException ex) {
                    request.setAttribute("error", "Ошибка обращения к БД.");
                    LOGGER.error("DB error: ", ex);
                    request.getRequestDispatcher("index.jsp").forward(request, response);
             } catch (NullDataException ex) {
                    request.setAttribute("error", "Книга не найдена.");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
             }
        } else {
            request.setAttribute("error", "Зарегистрируйтесь или авторизируйтесь для скачивания книги.");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }       
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}
